package com.game.api.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.game.api.annotation.Token;
import com.game.api.config.COSClientConf;
import com.game.api.interceptor.ApiAuthInterceptor;
import com.game.common.utils.MyUtils;
import com.game.common.utils.StringUtils;
import com.game.core.domain.PrStaff;
import com.game.core.domain.PrUser;
import com.game.core.domain.PrUserUrl;
import com.game.core.resp.ApiResult;
import com.game.core.resp.ResponeData;
import com.game.core.service.IPrStaffService;
import com.game.core.service.IPrUserService;
import com.game.core.service.IPrUserUrlService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: zbj
 * @time: 2020/5/21 12:52
 */
@Slf4j
@RestController
public class UserController {


    @Autowired
    private IPrStaffService prStaffService;


    @Autowired
    private IPrUserService prUserService;


    @Autowired
    private IPrUserUrlService prUserUrlService;


    /**
     * 通用上传请求
     */
    @Token(has = false)
    @PostMapping("/upload")
    public ResponeData uploadFile(MultipartFile file, HttpServletRequest request) throws Exception {

        try {
            String userId = request.getParameter("userId");
            PrUser byId = prUserService.getById(userId);
            // 判断文件是否为空，空则返回失败页面
            if (file.isEmpty()) {
                return ResponeData.builder().build().fail("上传文件为空！");
            }
            log.info(byId.toString());
            // 获取文件存储路径（绝对路径）
            // 获取原文件名
            String fileName = userId + MyUtils.getOrderId() + ".png";
//            String pathName = "/data/nginx/www/plImg/"+byId.getCountry() +File.separator + byId.getVillage()+File.separator + userId;
//            String urlName = "http://cdn.zbjlife.cn/plImg/" +byId.getCountry() +File.separator + byId.getVillage()+File.separator + userId;
////            String pathName = "C:\\Users\\Quokka\\Desktop\\1\\" + userId;
////            String urlName = "C:\\Users\\Quokka\\Desktop\\1\\" + userId;
//
//            // 创建文件实例
//            File filePath = new File(pathName, fileName);
//            // 如果文件目录不存在，创建目录
//            if (!filePath.getParentFile().exists()) {
//                filePath.getParentFile().mkdirs();
//                System.out.println("创建目录" + filePath);
//            }
//            // 写入文件
//            file.transferTo(filePath);

            String prefix = fileName.substring(fileName.lastIndexOf("."));
            File outfile = File.createTempFile(fileName,prefix);
            file.transferTo(outfile);

            String s = COSClientConf.uploadFile(fileName, outfile);
            if(StringUtils.isEmpty(s)){
                return ResponeData.builder().build().fail("上传文件失败！");
            }

            outfile.delete();

            ApiResult apiResult = ApiResult.builder().build()
                    .add("url", "http://cdn.zbjlife.cn" + "/" + fileName)
                    .add("fileUrl", File.separator + fileName);
            log.info(apiResult.toString());
            return ResponeData.builder().build().success(apiResult);
        } catch (Exception e) {
            return ResponeData.builder().build().fail("上传异常！");
        }

    }

    public static void main(String[] args) {
        File outfile = new File("C:\\Users\\zbj\\Pictures\\Camera Roll\\ChMkJ1e63leIYkTDAAkMl3OLxkgAAUo1AIlep0ACQyv356.jpg");
        String s = COSClientConf.uploadFile(outfile.getName(), outfile);
    }

    /**
     * 登录接口
     */
    @Token(has = false)
    @PostMapping("/login")
    public ResponeData login(HttpServletRequest request) throws Exception {
        try {
            ServletInputStream inputStream = request.getInputStream();
            String str = new String(inputStream.readAllBytes(), "utf-8");
            JSONObject josn = JSONObject.parseObject(str);
            QueryWrapper<PrStaff> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(PrStaff::getLoginName, josn.get("userName"));
            queryWrapper.lambda().eq(PrStaff::getPassword, josn.get("password"));
            PrStaff prStaff = prStaffService.getOne(queryWrapper);

            if (prStaff == null) return ResponeData.builder().build().fail("密码错误！");

            /* 生成TOKEN */
            String token = MyUtils.getUUID();
            ApiAuthInterceptor.tokenMap.put(token, prStaff);
            ApiResult apiResult = ApiResult.builder().build().add("token", token);

            return ResponeData.builder().build().success(apiResult);
        } catch (Exception e) {
            log.error("服务器异常: " + e.getMessage() + "\n" + MyUtils.getExceptionAllinformation(e));
            return ResponeData.builder().build().fail("服务器异常，请稍后再试！");
        }
    }


    /**
     * 获取人员信息
     */
    @PostMapping("/getUser")
    public ResponeData getUser(HttpServletRequest request) throws Exception {
        try {
            ServletInputStream inputStream = request.getInputStream();
            String str = new String(inputStream.readAllBytes(), "utf-8");
            JSONObject josn = JSONObject.parseObject(str);
            String id = josn.getString("id");
            String id_num = josn.getString("id_num");
            QueryWrapper<PrUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(PrUser::getId, id);
//            queryWrapper.lambda().eq(PrUser::getIdNum, id_num);
            PrUser prUser = prUserService.getOne(queryWrapper);
            if (prUser == null) return ResponeData.builder().build().fail("用户不存在！");

            int length = prUser.getIdNum().length();
            String substring = prUser.getIdNum().substring(length - 6, length);
            if(!id_num.equalsIgnoreCase(substring)) return ResponeData.builder().build().fail("身份证后6位不正确！");;

            //  搜索该用户是否评估记录过
            JSONObject data = new JSONObject();
            data.put("data", prUser);
            System.out.println(" prUser.getState().equals(1):" + prUser.getState().equals(1));
            data.put("ifEditor", prUser.getState().equals(1));
            return ResponeData.builder().build().success(data);
        } catch (Exception e) {
            log.error("服务器异常: " + e.getMessage() + "\n" + MyUtils.getExceptionAllinformation(e));
            return ResponeData.builder().build().fail("服务器异常，请稍后再试！");
        }
    }


    /**
     * 人员信息不符 插入备注
     */
    @PostMapping("/userMessageDiscrepancy")
    public ResponeData userMessageDiscrepancy(HttpServletRequest request) throws Exception {
        try {
            ServletInputStream inputStream = request.getInputStream();
            String str = new String(inputStream.readAllBytes(), "utf-8");
            JSONObject josn = JSONObject.parseObject(str);

            Integer id = josn.getInteger("id");
            String message = josn.getString("message");
            String token = josn.getString("token");

            PrStaff prStaff = ApiAuthInterceptor.tokenMap.get(token);

            // 修改的值
            PrUser prUser = new PrUser();
            prUser.setState(2);
            prUser.setMessage(message);
            prUser.setStaName(prStaff.getId());

            // where 条件
            UpdateWrapper<PrUser> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda().eq(PrUser::getId, id);

            if (!prUserService.update(prUser, updateWrapper)) {
                return ResponeData.builder().build().fail("修改失败！");
            }

            return ResponeData.builder().build().success();
        } catch (Exception e) {
            log.error("服务器异常: " + e.getMessage() + "\n" + MyUtils.getExceptionAllinformation(e));
            return ResponeData.builder().build().fail("服务器异常，请稍后再试！");
        }
    }


    /**
     * 插入用户调研表记录
     */
    @PostMapping("/saveUserResearch")
    public ResponeData saveUserResearch(HttpServletRequest request) throws Exception {
        try {
            ServletInputStream inputStream = request.getInputStream();
            String str = new String(inputStream.readAllBytes(), "utf-8");
            JSONObject json = JSONObject.parseObject(str);
            Integer userId = json.getInteger("userId");
            String token = json.getString("token");
            if (null == userId) return ResponeData.builder().build().fail("userId为空!");
            if (null == token) return ResponeData.builder().build().fail("token为空!");


            // 操作员
            {
                PrStaff prStaff = ApiAuthInterceptor.tokenMap.get(token);

                PrUser prUser = new PrUser();
                prUser.setState(1);
                prUser.setStaName(prStaff.getId());

                // where 条件
                UpdateWrapper<PrUser> updateWrapper = new UpdateWrapper<>();
                updateWrapper.lambda().eq(PrUser::getId, userId);

                if (!prUserService.update(prUser, updateWrapper)) {
                    return ResponeData.builder().build().fail("修改失败！");
                }
            }

            //  删除旧的调研数据
            {
                QueryWrapper<PrUserUrl> puu = new QueryWrapper<>();
                puu.lambda().eq(PrUserUrl::getUId, userId);
                prUserUrlService.remove(puu);

                //  删除服务器就图片

            }


            //  插入用户调研图片
            {
                JSONArray imgTypeData1 = json.getJSONArray("imgTypeData1");
                JSONArray imgTypeData2 = json.getJSONArray("imgTypeData2");
                JSONArray imgTypeData3 = json.getJSONArray("imgTypeData3");
                JSONArray imgTypeData4 = json.getJSONArray("imgTypeData4");
                JSONArray imgTypeData5 = json.getJSONArray("imgTypeData5");
                JSONArray imgTypeData6 = json.getJSONArray("imgTypeData6");
                JSONArray imgTypeData7 = json.getJSONArray("imgTypeData7");
                JSONArray imgTypeData8 = json.getJSONArray("imgTypeData8");
                JSONArray imgTypeData9 = json.getJSONArray("imgTypeData9");
                JSONArray imgTypeData10 = json.getJSONArray("imgTypeData10");
                JSONArray imgTypeData11 = json.getJSONArray("imgTypeData11");
                JSONArray imgTypeData12 = json.getJSONArray("imgTypeData12");
                JSONArray imgTypeData13 = json.getJSONArray("imgTypeData13");

                List<PrUserUrl> list = new ArrayList<>();
                getPrUserUrlData(list, imgTypeData1, 0, userId);
                getPrUserUrlData(list, imgTypeData2, 1, userId);
                getPrUserUrlData(list, imgTypeData3, 2, userId);
                getPrUserUrlData(list, imgTypeData4, 3, userId);
                getPrUserUrlData(list, imgTypeData5, 4, userId);
                getPrUserUrlData(list, imgTypeData6, 5, userId);
                getPrUserUrlData(list, imgTypeData7, 6, userId);
                getPrUserUrlData(list, imgTypeData8, 7, userId);
                getPrUserUrlData(list, imgTypeData9, 8, userId);
                getPrUserUrlData(list, imgTypeData10, 9, userId);
                getPrUserUrlData(list, imgTypeData11, 10, userId);
                getPrUserUrlData(list, imgTypeData12, 11, userId);
                getPrUserUrlData(list, imgTypeData13, 12, userId);

                prUserUrlService.saveBatch(list);
            }

            return ResponeData.builder().build().success();
        } catch (Exception e) {
            log.error("服务器异常: " + e.getMessage() + "\n" + MyUtils.getExceptionAllinformation(e));
            return ResponeData.builder().build().fail("服务器异常，请稍后再试！");
        }
    }

    //  遍历获取图片组
    public void getPrUserUrlData(List<PrUserUrl> list, JSONArray imgTypeData, int type, int userId) {
        for (int i = 0; i < imgTypeData.size(); i++) {
            JSONObject data = imgTypeData.getJSONObject(i);
            PrUserUrl prUserUrl = new PrUserUrl();
            prUserUrl.setUId(userId);
            prUserUrl.setType(type);
            prUserUrl.setUrl(data.getString("url"));
            prUserUrl.setLocalUrl(data.getString("fileUrl"));

            list.add(prUserUrl);
        }
    }

}
